import axios from 'axios'
import router from '@/router'

const baseURL = import.meta.env.VITE_API_BASE_URL || 'https://www.baddonkey.cn/agentApi'

const request = axios.create({
  baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    const { data } = response

    if (data.status === 'U0001') {
      return data.content
    } else if (data.status === 'A9001') {
      localStorage.removeItem('token')
      router.push('/login')
      return Promise.reject(new Error('登录已过期，请重新登录'))
    } else {
      return Promise.reject(new Error(data.message || '请求失败'))
    }
  },
  error => {
    if (error.response) {
      const { status } = error.response
      switch (status) {
        case 401:
          localStorage.removeItem('token')
          router.push('/login')
          break
        case 403:
          console.error('权限不足')
          break
        case 404:
          console.error('请求的资源不存在')
          break
        case 500:
          console.error('服务器内部错误')
          break
        default:
          console.error('网络错误')
      }
    } else {
      console.error('网络连接失败')
    }
    return Promise.reject(error)
  }
)

export default request